package com.wechar.pub_account;

import com.thoughtworks.xstream.XStream;
import com.wechar.pub_account.entity.Message;
import com.wechar.pub_account.util.SignUtil;
import com.wechar.pub_account.util.WeCharUtil;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/")
public class WeCharController {

    Logger logger = LoggerFactory.getLogger(WeCharController.class);

    @RequestMapping("/index")
    public String index(HttpServletRequest request, HttpSession session){
        return "index";
    }

    @RequestMapping(method = RequestMethod.GET)
    public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String signature = request.getParameter("signature");/// 微信加密签名
        String timestamp = request.getParameter("timestamp");/// 时间戳
        String nonce = request.getParameter("nonce"); /// 随机数
        String echostr = request.getParameter("echostr"); // 随机字符串

        PrintWriter out = response.getWriter();
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }

        out.flush();
        out.close();
    }

    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SAXReader reader = new SAXReader();
        InputStream ins = request.getInputStream();
        Element root = reader.read(ins).getRootElement();
        List<Element> list = root.elements();

        Map<String, String> requestParam = new HashMap<>();

        for (Element e : list) {
            requestParam.put(e.getName(), e.getText());
        }

        for(String key : requestParam.keySet()){
            logger.info(key+"："+requestParam.get(key));
        }

        //自动回复逻辑处理
        Message message = null;
        if ("V1001_TODAY_MUSIC".equals(requestParam.get("EventKey"))) {
            message = new Message(requestParam.get("ToUserName"), requestParam.get("FromUserName"), "https://music.163.com/#/discover/toplist");
        } else {
            message = new Message(requestParam.get("ToUserName"), requestParam.get("FromUserName"), new String("嗝哈哈哈哈哈哈".getBytes(), StandardCharsets.ISO_8859_1));
        }

        XStream xStream = new XStream();
        xStream.alias("xml", Message.class);
        String xml = xStream.toXML(message);
        PrintWriter printWriter = response.getWriter();

        printWriter.print(xml);
        printWriter.flush();
        printWriter.close();
    }

    @RequestMapping("/initMenu")
    @ResponseBody
    public String initMenu() throws Exception {
        return WeCharUtil.initMenu();
    }

    @RequestMapping("/getAccessToken")
    @ResponseBody
    public String getAccessToken() throws Exception {
        return WeCharUtil.getAccessToken();
    }

}